<template>
  <!-- 
    组件作用：
    每个博文单元的展示
   -->
  <div
    class="BlogItemBox"
    :class="{
      dark: themeRef.state.themeState == 'drak',
      light: themeRef.state.themeState == 'light',
      delete: deleteFlage,
    }"
  >
    <div class="type_0">
      <!-- 头部 -->
      <div class="title">
        <div class="headerImg">
          <router-link
            :to="{
              path: `/about/${uploadUserIdRef}`,
              params: { id: uploadUserIdRef },
            }"
          >
            <img :src="renderData.userInfo.headerImg" alt="我是头像" />
          </router-link>
        </div>
        <div class="nick">
          <router-link
            :to="{
              path: `/about/${uploadUserIdRef}`,
              params: { id: uploadUserIdRef },
            }"
          >
            {{ renderData.userInfo.nick }}
          </router-link>
          <br />
          <span>{{ renderData.blogUpTime }}</span>
          <span v-show="renderData.refwordUrl != 'NULL'">
            &nbsp; 转载自
            <router-link
              :to="{
                path: `/about/${refOriginBlogId}`,
                params: { id: refOriginBlogId },
              }"
              >{{ refUserInfoRef.nick }}</router-link
            >
          </span>
        </div>

        <div class="del" v-if="type" @click="deleteBlogFn(renderData.blogID)">
          删除
        </div>
        <div class="foc" v-else>
          <div
            class="focusOn"
            v-if="loginUserId != renderData.userID && atten == false"
            @click="focusOnFn"
            :class="{ dt: classDt }"
          >
            关注
          </div>
          <div class="focusOut" v-else title="无法对自己进行操作">已关注</div>
        </div>
      </div>
      <!-- 内容 -->
      <div class="content">
        <pre>{{ renderData.blogContent }}</pre>
        <div class="image" v-show="renderData.type == '1'">
          <el-image
            v-for="(item, index) in blogImageArrayRef"
            :key="item.id"
            class="imageBox"
            style="width: 100%; height: 100%"
            :src="item.thumbnail"
            :preview-src-list="srcList"
            :initial-index="index"
            fit="cover"
            alt="点击查看大图"
          />
        </div>
        <div class="video" v-show="renderData.type == '2'">
          <videoPlay
            v-bind="vedioOptionObj"
            :src="blogVideoRef.finallyUrlM3u8"
            :poster="blogVideoRef.captureCoverImage"
            :control="videoControlFlagRef"
          />
        </div>
      </div>

      <!-- 转发 -->
      <div class="operation">
        <div
          class="ref"
          @click="throttleFn(refwordBlogFn)"
          :class="{ active: reforwordRef }"
        >
          <i class="iconfont icon-31zhuanfa"></i>
          <span>{{ refNumber }}</span>
        </div>
        <div class="comm" @click="throttleFn(commSectionShowOrHide)">
          <i class="iconfont icon-31pinglun"></i>
          <span>{{ messageNumberRef }}</span>
        </div>
        <div
          class="like"
          :class="{ active: likeRef }"
          @click="throttleFn(like, renderData.blogID)"
          title="点赞/取消赞"
        >
          <i class="iconfont icon-31dianzan"></i>
          <span>{{ likeNumber }}</span>
        </div>
      </div>
    </div>
    <!-- 评论模块 -->
    <div class="commSection" v-if="showOrHideRef">
      <InputComm
        :option="InputCommOption"
        :blogID="renderData.blogID"
        @reflush="reflushFn"
      ></InputComm>
      <div class="wapper">
        <BlogMessage
          :blogID="renderData.blogID"
          :userID="renderData.userID"
          :key="messageRef"
        ></BlogMessage>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Vue, Options } from "vue-class-component";
import { useStore } from "vuex";
import InputComm from "../InputCommComp/InputComm.vue";
import BlogMessage from "../BlogMessageComp/BlogMessage.vue";
import ins from "../../utils/Axios";
import { ElMessage } from "element-plus";
import { throttle } from "../../utils/Tools";
import "vue3-video-play/dist/style.css";
import { videoPlay } from "vue3-video-play";
import { reactive } from "@vue/reactivity";

@Options({
  components: { InputComm, BlogMessage, videoPlay },
  mounted() {
    console.log(this.renderData);
    this.reforword = JSON.stringify(this.renderData);
    //这是一个被转发的博客
    if (this.renderData.refwordUrl != "NULL") {
      const renderObj_json = JSON.parse(this.renderData.blogContent);
      this.reforword = this.renderData.blogContent;
      this.renderData.type = renderObj_json.type;
      this.renderData.blogImg = renderObj_json.blogImg;
      this.renderData.blogVideo = renderObj_json.blogVideo;
      this.renderData.blogContent = renderObj_json.blogContent;
      this.refUserInfoRef = renderObj_json.userInfo;
      this.refOriginBlogId = renderObj_json.userID;
    }
    if (this.renderData.type == "1") {
      const arr = JSON.parse(this.renderData.blogImg);
      this.blogImageArrayRef = arr;
      arr.forEach((element: any) => {
        this.srcList.push(element.path);
      });
    }
    if (this.renderData.type == "2") {
      this.blogVideoRef = JSON.parse(this.renderData.blogVideo);
    }

    this.uploadUserIdRef = this.renderData.userID;
    // 是否关注
    this.atten = this.renderData.atten;
    // 是否转发
    this.reforwordRef = this.renderData.ref;
    // 是否点赞
    this.likeRef = this.renderData.like;
    // 点赞总数
    this.likeNumber = this.renderData.likeNumber;
    // 留言总数
    this.messageNumberRef = this.renderData.commNumber;
    this.refNumber = this.renderData.forwardNumber;
    // 获取当前登录用户
    this.loginUserId = localStorage.getItem("userID");
    // 获取博客ID
    this.blogId = this.renderData.blogID;
    // 博客权限
    this.Permissions = this.renderData.permissions;
  },
  props: {
    renderData: Object,
    type: Number,
  },
})
export default class BlogItem extends Vue {
  atten: boolean = false;
  // 权限
  Permissions: number = 1;
  themeRef: any = useStore();
  showOrHideRef: boolean = false;
  InputCommOption: object = {
    emoji: true,
    image: false,
    video: false,
    permissions: false,
    buttonText: "评论",
    placeholder: "请发表您的看法~~~~",
  };
  // 转发用户的ID
  refOriginBlogId: string = "";
  // 当前博客的发送者
  uploadUserIdRef: string = "";
  // 被转发人的信息
  refUserInfoRef: object = {};
  // 是否转发
  reforwordRef: boolean = false;
  // 是否点赞
  likeRef: boolean = false;
  // 点赞总数
  likeNumber: number = 0;
  // 留言总数
  messageRef: number = 0;
  //refNUmber
  // 转发总数
  refNumber: number = 0;
  messageNumberRef: number = 0;
  // 当前登录用户
  loginUserId: string = "";
  // 当前博客ID
  blogId: string = "";
  // 转发ID
  reforword: string = "";
  // 组图渲染数组
  blogImageArrayRef: Array<Object> = [];
  blogVideoRef: Object = {};
  // 渲染图片列表
  srcList: Array<string> = [];
  // 是否显示视频播放的控制台
  videoControlFlagRef: boolean = true;
  vedioOptionObj: Object = reactive({
    width: "540px", //播放器高度
    height: "300px", //播放器高度
    color: "#FF8200", //主题色
    title: "", //视频名称
    muted: false, //静音
    webFullScreen: false,
    speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
    autoPlay: false, //自动播放
    loop: false, //循环播放
    mirror: false, //镜像画面
    ligthOff: false, //关灯模式
    volume: 0.3, //默认音量大小
    type: "m3u8", //视频类型
  });
  // 留言框的显示/隐藏
  commSectionShowOrHide() {
    if (this.Permissions == -1 || this.Permissions == 3) {
      ElMessage.error("该用户设置了禁止留言！");
      return;
    }
    this.showOrHideRef = !this.showOrHideRef;
  }

  // 节流
  throttleFn(cb: Function) {
    throttle(cb, arguments);
  }

  // 点赞执行函数
  like(params: any) {
    let blogId: string = params[1];
    if (localStorage.getItem("userID")) {
      const userId = localStorage.getItem("userID");
      ins
        .get(this.likeRef ? "/blog/cancelLike" : "/blog/giveLike", {
          params: {
            userId,
            blogId,
          },
        })
        .then((res: object) => {
          this.likeRef = !this.likeRef;
          if (this.likeRef) {
            this.likeNumber++;
          } else {
            this.likeNumber--;
          }
        })
        .catch((err: object) => {
          ElMessage.error("发生未知错误！");
        });
    } else {
      ElMessage.error("您还未登录！");
    }
  }

  // 强制刷新组件
  reflushFn() {
    this.messageNumberRef++;
    this.messageRef = Math.random();
  }

  // 转发
  refwordBlogFn() {
    if (this.Permissions == -1 || this.Permissions == 2) {
      ElMessage.error("该用户设置了禁止转发！");
      return;
    }
    if (localStorage.getItem("userID")) {
      if (this.reforwordRef) {
        ins
          .post("/blog/cancelRefBlog", {
            blogId: this.blogId,
          })
          .then((res: any) => {
            if (res.data.flag) {
              this.refNumber--;
              this.reforwordRef = false;
            } else {
              ElMessage.error("转发失败！");
            }
          });
      } else {
        ins
          .post("/blog/refBlog", {
            refwordUrl: this.blogId,
            blogContent: this.reforword,
          })
          .then((res: any) => {
            if (res.data.flag) {
              this.refNumber++;
              this.reforwordRef = true;
            } else {
              ElMessage.error("转发失败！");
            }
          });
      }
    } else {
      ElMessage.error("您还未登录！");
    }
  }

  classDt: boolean = false;
  // 关注
  focusOnFn() {
    if (localStorage.getItem("userID")) {
      ins
        .post("/user/focusOnUserById", { followedUserId: this.uploadUserIdRef })
        .then((res: any) => {
          const { data } = res;
          if (data.flag) {
            this.atten = true;
            this.classDt = true;
          }
        });
    } else {
      ElMessage.error("您还未登录！");
    }
  }

  //删除标识符
  deleteFlage: boolean = false;
  deleteBlogFn(blogId: String) {
    ins
      .post("/blog/deleteBlog", { blogId })
      .then((res: any) => {
        const { data } = res;
        if (data.flag) {
          this.deleteFlage = true;
          ElMessage.success("删除成功！");
        } else {
          ElMessage.error("删除失败请重试！");
          return;
        }
      })
      .catch(() => {
        ElMessage.error("删除失败请重试！");
        return;
      });
  }
}
</script>

<style lang="less" scoped>
@import url("../../assets/less/global.less");
@import url("./index.less");
</style>